package gui.edt.swingutilities;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.Timer;

public class ButtonFlick extends JPanel {

	boolean mutex = true;
	private JButton button = new JButton("COLOR");
	boolean timeSTOPED = false;
	Timer time;

	public ButtonFlick() {
		// TODO Auto-generated constructor stub
		setPreferredSize(new Dimension(200, 200));
	}

	@Override
	public void paint(Graphics g) {
		// TODO Auto-generated method stub
		super.paint(g);
		Graphics2D g2D = (Graphics2D) g;
		int width = this.getWidth() / 3;
		int height = this.getHeight() / 3;
		int x = getWidth() / 3;
		int y = getHeight() / 3;
		if (!mutex) {
			g2D.setColor(Color.red);
			x -= 4;
			g2D.fillOval(x, y, width, height);

			g2D.setColor(Color.red);
			x -= 4;
			g2D.drawOval(x, y, width, height);
		} else {
			g2D.setColor(Color.red);
			x += 4;
			g2D.fillOval(x, y, width, height);
			
			g2D.setColor(Color.red);
			x += 4;
			g2D.drawOval(x, y, width, height);
		}
	}

	private void flickV2() {
		int delay = 100;
		Timer timer = new Timer(delay, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				if (mutex) {
//					setBackground(Color.RED);
					mutex = false;
//					button.setBackground(Color.GREEN);
				} else {
//					setBackground(Color.GREEN);
					mutex = true;
//					button.setBackground(Color.RED);
				}
				repaint();
			}
		});
		timer.start();
	}

	private void flick() {
		SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

			@Override
			protected Object doInBackground() throws Exception {
				while (true) {
					Thread.sleep(1000);
					setBackground(Color.green);
					Thread.sleep(1000);
					setBackground(Color.red);
				}
				// return null;
			}

		};
		sw.execute();
	}

	private void fButton() {
		this.add(button);
		int delay = 100;
		time = new Timer(delay, new ActionListener() {

			private int c = 0;
			
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				c++;
				if (!mutex) {
					button.setBackground(Color.GREEN);
					mutex = true;
				} else {
					button.setBackground(Color.RED);
					mutex = false;
				}
				if (c == 100) {
					timeSTOPED = true;
					time.stop();
				}
				System.out.println(c);
			}
		});
		time.start();
	}

	public static void main(String[] args) {
		JFrame frame = new JFrame();

		ButtonFlick button = new ButtonFlick();
		frame.getContentPane().add(button);

//		 button.flick();
		 button.flickV2();
//		button.fButton();

		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
	}
}
